import type { BasicTableProps, FetchParams } from "../types/table";
import type { FormProps } from "@/components/Form";
import { isFunction } from "@/utils/is";
import { useMemo, useRef } from "react";

export function useTableForm(
	propsRef: BasicTableProps,
	slots: SlotsComponent,
	fetch: (opt?: FetchParams | undefined) => Promise<void>,
	getLoading: boolean | undefined
) {
	const show = useRef(true);

	const getFormProps = useMemo((): Partial<FormProps> => {
		const { formConfig } = propsRef;
		const { submitButtonOptions } = formConfig || {};
		return {
			showAdvancedButton: true,
			showActionButtonGroup: true,
			...formConfig,
			submitButtonOptions: { loading: getLoading, ...submitButtonOptions },
			compact: true as boolean
		};
	}, [propsRef.formConfig]);

	const getFormSlotKeys: string[] = useMemo(() => {
		const keys = Object.keys(slots);
		return keys.map(item => (item.startsWith("form-") ? item : null)).filter(item => !!item) as string[];
	}, []);

	function replaceFormSlotKey(key: string) {
		if (!key) return "";
		return key?.replace?.(/form-/, "") ?? "";
	}

	function handleSearchInfoChange(info: Recordable) {
		const { handleSearchInfoFn } = propsRef;
		if (handleSearchInfoFn && isFunction(handleSearchInfoFn)) info = handleSearchInfoFn(info) || info;

		fetch({ searchInfo: info, page: 1 });
	}

	function getShowForm() {
		return show.current;
	}

	function setShowForm(flag: boolean) {
		show.current = flag;
	}

	return {
		getFormProps,
		replaceFormSlotKey,
		getFormSlotKeys,
		handleSearchInfoChange,
		getShowForm,
		setShowForm
	};
}
